﻿using IM.Easy.Api.AccountManage;
using IM.Easy.Api.Hubs;
using IM.Easy.AuthorizationServices.Dtos;
using IM.Easy.AuthorizationServices.IServices;
using IM.Easy.Core.AppContext;
using IM.Easy.Core.Attributes;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;
using IM.Easy.SystemServices.Services;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;

namespace IM.Easy.Api.Controllers.System
{
    public class AccountController : ControllerBase
    {
        private readonly IPermissionService _permissionService;
        private readonly IMenuService _menuService;
        private readonly IVueRouteService vueRouteService;
        private readonly AccountService accountService;
        private readonly IHubContext<UserHub> _hubContext;
        private readonly IUserService _userService;
        public AccountController(IPermissionService permissionService, IMenuService menuService, IVueRouteService vueRouteService, AccountService accountService, IHubContext<UserHub> hubContext)
        {
            _permissionService = permissionService;
            _menuService = menuService;
            this.vueRouteService = vueRouteService;
            this.accountService = accountService;
            _hubContext = hubContext;
        }

        /// <summary>
        /// 登录
        /// </summary>
        [Api(Name = "登录", Required = true)]
        [HttpPost("signin")]
        public async Task<AccountInfo> SignIn()
        {
            var account = accountService.SignIn();
            return account;
        }

        /// <summary>
        /// 注销登录
        /// </summary>
        [Api(Name = "注销", Required = true, AllowAnonymous = true)]
        [HttpPost("logout")]
        public void LoginOut()
        {
            if (ImApp.User.Id > 0)
            {
                //退出登录  清除用户缓存数据
                accountService.SignOut();
                //记录日志

            }

        }

        /// <summary>
        /// 获取当前登录账户权限信息
        /// </summary>
        [Api(Name = "获取账号信息", Required = true)]
        [HttpGet("info")]
        public AccountInfo GetAccountInfo()
        {
            return accountService.GetCurrent();
        }

        /// <summary>
        /// 获取账户下面的路由信息
        /// </summary>
        /// <returns></returns>
        [Api(Name = "获取账号路由数据", Required = true)]
        [HttpGet("routes")]
        public List<VueRoute> GetRouters()
        {
            var user = ImApp.User;
            var menusTree = user.IsSuperAdmin ? _menuService.GetMenuTree() : _menuService.GetMenuTreeByUserId(user.Id);
            var routes = vueRouteService.GenerateRoute(menusTree);
            return routes;
        }
    }
}
